package com.tssf.car_manage.controller;


import com.tssf.car_manage.entity.Admin;
import com.tssf.car_manage.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Random;

@Controller
public class LoginController {

    private final AdminService adminService;

    @Autowired
    public LoginController(AdminService adminService) {
        this.adminService = adminService;
    }
    @GetMapping("/login")
    public String showLogin(@RequestParam(required = false) String expired, Model model) {
        if ("true".equals(expired)) {
            model.addAttribute("msg", "会话已过期，请重新登录");
        }
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        @RequestParam("userType") String userType,
                        Model model, HttpSession session) {
        try {
            // 验证用户是否存在
            List<Admin> adminList = adminService.getAdminByUsername(username);
            if (adminList == null || adminList.isEmpty()) {
                model.addAttribute("msg", "用户不存在");
                return "login";
            }

            Admin admin = adminList.get(0);

            // 验证密码
            if (!admin.getPassword().equals(password)) {
                model.addAttribute("msg", "密码错误");
                return "login";
            }

            // 验证角色
            int selectedRole = "ADMIN".equals(userType) ? 1 : 0; // 假设1是管理员，0是普通用户
            if (admin.getRole() != selectedRole) {
                model.addAttribute("msg", "该用户不是" + ("ADMIN".equals(userType) ? "超级管理员" : "普通管理员用户"));
                return "login";
            }

            // 登录成功，设置session
            session.setAttribute("loginUser", admin.getUsername());
            session.setAttribute("loginRole", admin.getRole());

            return "redirect:/chart/refresh";
        } catch (Exception e) {
            model.addAttribute("msg", "登录异常: " + e.getMessage());
            return "login";
        }
    }
    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        // 使当前session失效
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();  // 这会清除整个session
        }
        return "redirect:/login?logout";  // 重定向到登录页并带退出参数
    }

}




